package com.zhengwl.study.datastruct;

import java.util.Arrays;

public class SequenceList<T> {
	private int DEFAULT_SIZE = 16;
	// 保存数组长度
	private int capacity;
	private Object[] elementData;
	// 保存顺序表中当前元素个数
	private int size = 0;

	public SequenceList() {
		capacity = DEFAULT_SIZE;
		elementData = new Object[capacity];
	}

	public SequenceList(T element) {
		this();
		elementData[0] = element;
		size++;
	}

	/**
	 * 以指定长度数组创建顺序线性表
	 * 
	 * @param element
	 * @param size
	 */
	public SequenceList(T element, int size) {
		capacity = 1;
		while (capacity < size) {
			capacity <<= 1;
		}
		elementData = new Object[capacity];
		elementData[0] = element;
		size++;
	}

	/**
	 * 获取线性表大小
	 * 
	 * @return
	 */
	public int length() {
		return size;
	}

	@SuppressWarnings("unchecked")
	public T get(int i) {
		if (i < 0 || i > size - 1) {
			throw new IndexOutOfBoundsException("线性表索引越界");
		}
		return (T) elementData[i];
	}

	public int locate(T element) {

		for (int i = 0; i < elementData.length; i++) {
			if (element.equals(elementData[i])) {
				return i;
			}
		}
		return -1;
	}

	public void insert(T element, int index) {
		if (index < 0 || index > size - 1) {
			throw new IndexOutOfBoundsException("线性表索引越界");
		}
		ensureCapactiy(size + 1);
		// 将指定索引处之后的所有元素向后移动一格
		System.arraycopy(elementData, index, elementData, index + 1, size - index);
		elementData[index] = element;
		size++;
	}

	/**
	 * 在线性表末尾插入一个元素
	 * 
	 * @param element
	 */
	public void add(T element) {
		insert(element, size);
	}

	private void ensureCapactiy(int minCapacity) {
		if (capacity < minCapacity) {
			//不断地将capacity*2 直到capacity大于minCapacity
			while (capacity < minCapacity) {
				capacity <<= 1;
			}
			elementData = Arrays.copyOf(elementData, capacity);
		}
	}

	/**
	 * 删除顺序线性表中指定索引处的元素
	 * 
	 * @param index
	 * @return
	 */
	public T delete(int index) {
		if (index < 0 || index > size - 1) {
			throw new IndexOutOfBoundsException("线性表索引越界");
		}
		@SuppressWarnings("unchecked")
		T oldValue = (T) elementData[index];
		int numMoved = size - index - 1;
		if (numMoved > 0) {
			System.arraycopy(elementData, index + 1, elementData, index, numMoved);
		}
		elementData[--size] = null;
		return oldValue;
	}

	/**
	 * 删除线性表最后一个元素
	 * 
	 * @return
	 */
	public T remove() {
		return delete(size - 1);
	}

	public boolean empty() {
		return size == 0;
	}

	public void clear() {
		// elementData=null;
		Arrays.fill(elementData, null);
		size = 0;
	}

	public String toString() {
		if (size == 0) {
			return "[]";
		} else {
			StringBuilder sb = new StringBuilder("[");
			for (int i = 0; i < elementData.length; i++) {
				sb.append(elementData[i].toString() + ",");
			}
			int len = sb.length();
			return sb.delete(len - 1, len).append("]").toString();
		}
	}
}
